package com.sunday.scoremanager.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.adapter.CommonAdapter;
import com.sunday.common.widgets.adapter.ViewHolder;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.scoremanager.R;
import com.sunday.scoremanager.adapter.OrderAdapter;
import com.sunday.scoremanager.base.BaseApp;
import com.sunday.scoremanager.base.BaseLazyFragment;
import com.sunday.scoremanager.entity.Order;
import com.sunday.scoremanager.http.ApiClient;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by 刘涛 on 2017/10/26.
 */

public class IndexFragment extends BaseLazyFragment {


    @Bind(R.id.news_num)
    TextView newsNum;
    @Bind(R.id.btn_code)
    ImageView btnCode;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    private OrderAdapter adapter;
    private LinearLayoutManager layoutManager;
    private List<Order> dataSet = new ArrayList<>();
    private long memberId;

    public static IndexFragment newInstance() {
        IndexFragment fragment = new IndexFragment();
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isPrepared = true;
        lazyLoad();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_index, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        if (!isPrepared || !isVisible) {
            return;
        }
        initRefreshLayout();
        isPrepared = false;


    }

    private int pageNo = 1;
    private boolean isCanLoadMore;


    private void initRefreshLayout() {
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new OrderAdapter(mContext, dataSet);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).drawable(R.drawable.shape_divider_width).build());
        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (isCanLoadMore) {
                    pageNo++;
                    getData();
                }else {
                    refreshlayout.finishLoadmore();
                }
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNo = 1;
                getData();
            }
        });
        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getData();
            }
        });
        newsNum.setVisibility(View.GONE);
        memberId = BaseApp.getInstance().getMember().getSellerId();
        getData();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    private void getData() {
        Call<ResultDO<List<Order>>> call = ApiClient.getApiAdapter().getOrderList(memberId, 2, pageNo, Constants.PAGE_SIZE);
        call.enqueue(new Callback<ResultDO<List<Order>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Order>>> call, Response<ResultDO<List<Order>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadmore();
                if (response.body().getCode() == 0) {
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    if (response.body().getResult() == null) {
                        return;
                    }
                    dataSet.addAll(response.body().getResult());
                    if (dataSet.size() > 0) {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                    if (response.body().getResult() != null && response.body().getResult().size() == Constants.PAGE_SIZE) {
                        isCanLoadMore = true;
                    } else {
                        isCanLoadMore = false;
                    }
                    adapter.notifyDataSetChanged();

                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Order>>> call, Throwable t) {
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadmore();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    @OnClick({R.id.fl_news, R.id.btn_code})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.fl_news:
                intent = new Intent(mContext, MyMessageActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_code:
                intent = new Intent(mContext, MyQrCodeActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

}
